<template>
  <basic-container>
    <avue-crud
      ref="crud"
      v-model="form"
      :page.sync="page"
      :data="tableData"
      :table-loading="tableLoading"
      :option="tableOption"
      :before-open="beforeOpen"
      @on-load="getList"
      @search-change="searchChange"
      @search-reset="searchpManageReset"
    >
      <template slot="registerTimeSearch">
        <el-date-picker
          v-model="retime"
          type="datetimerange"
          range-separator="至"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </template>
      <template #labelListForm="{ type }">
        <div v-if="type === 'view'">
          <div>
            <span>运营人员标记：</span>
            <el-tag
              v-for="tag in form.operatorLabelList"
              :key="tag.id"
              class="tags-item"
            >
              {{ tag.name }}
            </el-tag>
          </div>
          <div v-if="form.labelList">
            <span>用户自己标记：</span>
            <el-tag
              v-for="tag in form.labelList"
              :key="tag.id"
              class="tags-item"
            >
              {{ tag.name }}
            </el-tag>
          </div>
        </div>
      </template>
      <template slot="menuLeft">
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="add"
        >
          新增
        </el-button>
        <el-button
          size="small"
          type="primary"
          :disabled="isFlag"
          @click="exportExcel"
        >
          导出
        </el-button>
        <el-button
          class="filter-item"
          type="primary"
          size="small"
          @click="$refs.excelUpload.show()"
        >
          批量导入
        </el-button>
        <el-button
          size="small"
          type="primary"
          @click="downloadTemplate"
        >
          下载模板
        </el-button>
      </template>
      <template
        slot="menu"
        slot-scope="scope"
      >
        <el-button
          type="text"
          size="small"
          icon="el-icon-edit"
          @click="edit(scope.row, scope.index)"
        >
          修改
        </el-button>
      </template>
    </avue-crud>
    <editPopup
      v-model="editVisible"
      :user-id="userId"
      @success="(val) => getList(page, val)"
    ></editPopup>
    <addPopup
      v-model="addVisible"
      @success="(val) => getList(page, val)"
    ></addPopup>
    <excel-upload
      ref="excelUpload"
      title="批量导入"
      url="/api/app/appuser/import"
      @refreshDataList="getList"
    ></excel-upload>
  </basic-container>
</template>

<script>
import { fetchList, getObj } from '@/api/app/customer';
import { exportUserTemplate } from '@/api/admin/user';
import { tableOption } from '@/const/crud/customer/manage';
import { mapGetters } from 'vuex';
import crudMixins from '@/mixins/crud';
import editPopup from './components/editPopup.vue';
import addPopup from './components/addPopup.vue';
import ExcelUpload from '@/components/upload/excel.vue';
import request from '@/router/axios';
import moment from 'moment';

export default {
  name: 'customerManage',
  components: { ExcelUpload, editPopup, addPopup },
  mixins: [crudMixins],
  data() {
    return {
      editVisible: false,
      form: {},
      tableOption: tableOption(),
      userId: null,
      addVisible: false,
      isFlag: false,
      retime: '',
      registerTimeDefaultValue: [],
    };
  },
  computed: {
    ...mapGetters(['permissions']),
  },
  created() {
    const currentDate = moment(); // 获取当前时间
    const lastMonthDate = moment(currentDate).subtract(1, 'month'); // 减去一个月
    this.registerTimeDefaultValue = [
      lastMonthDate.format('YYYY-MM-DD HH:mm:ss'), // 上个月的开始时间
      currentDate.format('YYYY-MM-DD HH:mm:ss'), // 当前时间
    ];
    this.retime = this.registerTimeDefaultValue;
  },
  mounted() {},
  methods: {
    searchpManageReset() {
      this.retime = '';
      this.searchForm = {};
      this.getList();
    },
    edit(row) {
      this.editVisible = true;
      this.userId = row.userId;
    },
    add() {
      this.addVisible = true;
    },
    // 列表查询
    getList(page, refresh) {
      if (refresh) {
        this.page.current = 1;
        this.page.currentPage = 1;
      }
      this.tableLoading = true;
      const timeObj = {};
      if (this.retime && this.retime.length) {
        this.searchForm.registerTime = this.retime;
      }
      if (this.searchForm.registerTime && this.searchForm.registerTime.length) {
        timeObj.registerDateStart = this.searchForm.registerTime[0];
        timeObj.registerDateEnd = this.searchForm.registerTime[1];
      }
      fetchList(
        Object.assign(
          {
            current: this.page.currentPage,
            size: this.page.pageSize,
          },
          this.searchForm,
          timeObj
        )
      )
        .then((response) => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    // 打开前的拦截
    async beforeOpen(done, type) {
      if (type !== 'add') {
        const res = await getObj(this.form.userId);
        this.form = { ...res.data.data };
      }
      this.form.avatar = this.form.avatar
        ? this.form.avatar
        : '/img/default-avatar.png';
      done();
    },
    async downloadTemplate() {
      const res = await exportUserTemplate();
      if (res.data.data) {
        this.downloadExcel(res.data.data);
      }
    },
    downloadExcel(url) {
      const urls = url.split('/');
      this.downBlobFile(url, {}, urls[urls.length - 1]);
    },
    async exportExcel() {
      const timeObj = {};
      if (this.searchForm.registerTime && this.searchForm.registerTime.length) {
        timeObj.registerDateStart = this.searchForm.registerTime[0];
        timeObj.registerDateEnd = this.searchForm.registerTime[1];
      }
      const params = Object.assign(this.searchForm, timeObj);
      this.downBlobFile('/app/appuser/export', params, '客户列表.xlsx');
    },
    downBlobFile(url, query, fileName) {
      this.isFlag = true;
      return request({
        url: url,
        method: 'get',
        responseType: 'blob',
        params: query,
      })
        .then((response) => {
          this.isFlag = false;
          // 处理返回的文件流
          const blob = response.data;
          if (blob && blob.size === 0) {
            this.$notify.error('内容为空，无法下载');
            return;
          }
          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName;
          document.body.appendChild(link);
          link.click();
          window.setTimeout(function () {
            window.URL.revokeObjectURL(blob);
            document.body.removeChild(link);
          }, 0);
        })
        .catch(() => {
          this.isFlag = false;
        });
    },
  },
};
</script>
